let express = require("express");
let router = express.Router();
const bodyParser = require("body-parser");
const { getDb, saveDb } = require("../utils/db.js");
const { getToken, setToken } = require("../utils/token.js");

router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

// 登录请求
router.post("/login", async (req, res) => {
	console.log("登录请求", req.url);
	let info = req.body;
	console.log(req.body);
	let name = info["account"];
	let password = info["password"];
	const db = await getDb().catch((err) => {
		console.log(err);
		res.status(500).json({
			error: err.message,
		});
	});
	let userList = db["user"];
	let passed = false;

	for (let index = 0; index < userList.length; index++) {
		const element = userList[index];
		if (element["account"] === name && element["password"] === password) {
			passed = true;
			console.log("账号密码匹配成功");
			setToken(element["account"], element["password"])
				.then((value) => {
					res.setHeader("Authorization", value);
					res.status(200).json([element["account"], element["password"]]);
					res.end();
				})
				.catch((err) => {
					console.log(err);
				});
		}
	}
	if (!passed) res.status(403).json("账号或密码错误！");
});

// 注册请求：注册后需要重新进行登录
router.post("/register", async (req, res) => {
	console.log("注册请求");
	const registerInfo = req.body;
	let db = await getDb().catch((err) => {
		console.log(err);
	});
	let users = db["user"];
	// 判断是否account重复
	for (let index = 0; index < users.length; index++) {
		const element = users[index];
		const accoutItem = element.account;
		console.log(accoutItem, registerInfo.account);
		if (registerInfo.account === accoutItem) {
			console.log("account has exits");
			return res.send({ error: "account has exits" });
		}
	}
	registerInfo.experimentTimes = 0;
	registerInfo.historyStimulation = [];

	db["user"].push(registerInfo);
	saveDb(db).catch((err) => {
		console.log(err);
	});
	res.end("Register success!");
});

// 注销请求，其实前端销毁即可

// 请求服务器资源;
router.get("/echarts", (req, res) => {
	res.end();
});

// 请求历史记录
router.post("/records/:username", async (req, res) => {
	let username = req.params.username;
	const db = await getDb();
	let userList = db["user"];
	let passed = false;

	for (let index = 0; index < userList.length; index++) {
		const element = userList[index];
		if (element["account"] === username) {
			res.status(200).json(element["historyStimulation"]);
			console.log("返回历史模拟数据");
			passed = true;
			res.end();
		}
	}

	if (!passed) res.status(404).json("错误！没有相关历史记录");
});

// 获取详细个人信息
router.post("/info/:username", async (req, res) => {
	let username = req.params.username;
	const db = await getDb().catch((err) => {
		console.log(err);
	});
	let userList = db["user"];
	let passed = false;

	for (let index = 0; index < userList.length; index++) {
		const element = userList[index];
		if (element["account"] === username) {
			res.status(200).json(element);
			console.log("返回完整个人信息");
			passed = true;
			res.end();
		}
	}

	if (!passed) res.status(404).json("错误！没有相关历史记录");
});

module.exports = router;
